import { Singleton } from "../Common";
import { EventTypeEnum } from "../Enum";

interface IItem {
    ctx: unknown,
    fun: Function
}
export class EventManager extends Singleton {

    static get Ins() {
        return super.GetInstance<EventManager>()
    }

    private map: Map<EventTypeEnum, IItem[]> = new Map()

    on(name: EventTypeEnum, fun: Function, ctx: unknown) {
        if (this.map.has(name)) {
            this.map.get(name).push({ ctx, fun })
        } else {
            this.map.set(name, [{ ctx, fun }])
        }
    }

    off(name: EventTypeEnum, fun: Function, ctx: unknown) {
        if (this.map.has(name)) {
            const index = this.map.get(name).findIndex(v => v.fun === fun && v.ctx === ctx)
            index > -1 && this.map.get(name).splice(index, 1)
        }
    }

    emit(name: EventTypeEnum, ...arg: any) {
        if (this.map.has(name)) {
            this.map.get(name)?.forEach(({ fun, ctx }) => {
                fun.apply(ctx, arg)
            })
        }
    }

    clear() {
        this.map = new Map()
    }
}